package com.sunshine.wrongquestionset.activity.my_subject

import android.content.Intent
import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputEditText
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.activity.question.QuestionActivity
import com.sunshine.wrongquestionset.callback.OnClickListener
import com.sunshine.wrongquestionset.room.entity.SubjectEntity
import kotlinx.android.synthetic.main.activity_my_subject.*

class MySubjectActivity : BaseActivity() {

    private lateinit var viewModel: MySubjectViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_subject)
        setTitle(getString(R.string.label_my_subject))

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(MySubjectViewModel::class.java)

        viewModel.getMySubject(getLoginUserId()).observe(this, Observer {list ->
            recyclerView.setLayoutManager(LinearLayoutManager(this))
            val adapter = MySubjectAdapter(
                list as ArrayList<SubjectEntity>,
                viewModel,
                this,
                object : OnClickListener {
                    override fun onClick(position: Int) {
                        val builder = MaterialAlertDialogBuilder(this@MySubjectActivity)

                        var dialog: AlertDialog? = null

                        builder.apply {
                            val menuView = LayoutInflater.from(this@MySubjectActivity).inflate(R.layout.view_subject_menu, null, false)
                            val show: MaterialButton = menuView.findViewById(R.id.button_show)
                            val edit: MaterialButton = menuView.findViewById(R.id.button_edit)
                            val toDelete: MaterialButton = menuView.findViewById(R.id.button_to_delete)

                            show.setOnClickListener {
                                val intent = Intent(this@MySubjectActivity, QuestionActivity::class.java)
                                intent.putExtra("type", QuestionActivity.TYPE_SUBJECT)
                                intent.putExtra("subjectId", list[position].id)
                                startActivity(intent)
                                dialog?.cancel()
                            }
                            edit.setOnClickListener {
                                dialog?.cancel()
                                editSubject(list[position])
                            }
                            toDelete.setOnClickListener {
                                val builder1 = MaterialAlertDialogBuilder(this@MySubjectActivity)
                                builder1.apply {
                                    setTitle(getString(R.string.warning_title))
                                    setMessage(Html.fromHtml(getString(R.string.warning_message)))
                                    setPositiveButton(getString(R.string.delete_cancel)) {_, _ ->

                                    }
                                    setNegativeButton(getString(R.string.delete)) {_, _ ->
                                        try {
                                            if (list.size <= 1) {
                                                Snackbar.make(subject_root, getString(R.string.delete_subject_fail), Snackbar.LENGTH_SHORT).show()
                                            } else {
                                                viewModel.toDelete(list[position])
                                                Snackbar.make(subject_root, getString(R.string.delete_success), Snackbar.LENGTH_SHORT).show()
                                            }
                                        }catch (e: Exception) {
                                            //虽然用捕获异常的方式不大好，但是方便...
                                            Snackbar.make(subject_root, getString(R.string.delete_subject_fail_1), Snackbar.LENGTH_SHORT).show()
                                        }

                                        dialog?.cancel()
                                    }
                                }
                                builder1.create().show()
                            }
                            setView(menuView)
                        }
                        dialog = builder.create()
                        dialog.show()
                    }

                    override fun onLongClick(position: Int) {

                    }
                }
            )

            recyclerView.setAdapter(adapter)
        })

        fab_add_subject.setOnClickListener {
            addSubject()
        }
    }

    /**
     * 添加信息
     */
    private fun addSubject() {
        editSubject(null)
    }

    /**
     * 修改科目信息
     * @param subjectEntity 科目实体
     */
    private fun editSubject(subjectEntity: SubjectEntity?) {
        val builder = MaterialAlertDialogBuilder(this)
        builder.apply {
            val view = LayoutInflater.from(this@MySubjectActivity).inflate(R.layout.view_add_subject, null, false)
            val nameEditText: TextInputEditText = view.findViewById(R.id.edit_add_subject)

            nameEditText.setText(subjectEntity?.name)

            setView(view)
            setTitle(if (subjectEntity == null) getString(R.string.add_subject) else getString(R.string.edit_subject))
            setPositiveButton("确定") {_, _ ->
                val name = nameEditText.text?.toString()
                if (name.isNullOrBlank()) {
                    Snackbar.make(subject_root, getString(R.string.subject_error), Snackbar.LENGTH_SHORT).show()
                } else {
                    //添加模式
                    if (subjectEntity == null) {
                        viewModel.addSubject(getLoginUserId(), name)
                        Snackbar.make(subject_root, getString(R.string.add_subject_success), Snackbar.LENGTH_SHORT).show()
                    }
                    //编辑模式
                    else {
                        subjectEntity.name = name
                        viewModel.updateSubject(subjectEntity)
                        Snackbar.make(subject_root, getString(R.string.edit_subject_success), Snackbar.LENGTH_SHORT).show()
                    }
                }
            }
        }
        builder.create().show()
    }
}